<?php

namespace App\Services;

use Illuminate\Http\Request;

/**
 * WordPress 查询参数处理服务
 *
 * 负责将HTTP请求参数转换为WordPress WP_Query可用的参数格式
 */
class WPQueryService
{
    /**
     * 将请求参数转换为WP_Query参数
     *
     * @param Request $request
     * @return array
     */
    public static function buildQueryParams(Request $request): array
    {
        $params = self::getBasicParams($request);

        // 合并各种查询参数
        $params = array_merge($params, self::getPostParams($request));
        $params = array_merge($params, self::getTaxonomyParams($request));
        $params = array_merge($params, self::getAuthorParams($request));
        $params = array_merge($params, self::getDateParams($request));
        $params = array_merge($params, self::getSearchParams($request));
        $params = array_merge($params, self::getStickyParams($request));

        return array_filter($params, function ($value) {
            return $value !== null && $value !== '';
        });
    }

    /**
     * 获取基础查询参数
     */
    private static function getBasicParams(Request $request): array
    {
        return [
            'post_type' => $request->get('post_type', 'post'),
            'post_status' => $request->get('post_status', 'publish'),
            'posts_per_page' => (int) $request->get('limit', 10),
            'paged' => (int) $request->get('page', 1),
            'orderby' => $request->get('orderby', 'date'),
            'order' => $request->get('order', 'DESC'),
        ];
    }

    /**
     * 获取文章相关参数
     */
    private static function getPostParams(Request $request): array
    {
        $params = [];

        // 文章ID查询
        if ($request->has('ids')) {
            $params['post__in'] = array_map('intval', explode(',', $request->get('ids')));
        }

        if ($request->has('not_ids')) {
            $params['post__not_in'] = array_map('intval', explode(',', $request->get('not_ids')));
        }


        return $params;
    }

    /**
     * 获取分类法相关参数（分类、标签等）
     */
    private static function getTaxonomyParams(Request $request): array
    {
        $params = [];

        // 分类查询
        if ($request->has('cat')) {
            $params['cat'] = $request->get('cat');
        }
        if ($request->has('cat_ids')) {
            $params['category__in'] = array_map('intval', explode(',', $request->get('cat_ids')));
        }

        if ($request->has('not_cat_ids')) {
            $params['category__not_in'] = array_map('intval', explode(',', $request->get('not_cat_ids')));
        }

        // 标签查询 - 使用tag参数传递标签ID
        if ($request->has('tag')) {
            $params['tag_id'] = (int) $request->get('tag');
        }

        if ($request->has('tag_ids')) {
            $params['tag__in'] = array_map('intval', explode(',', $request->get('tag_ids')));
        }

        if ($request->has('not_tag_ids')) {
            $params['tag__not_in'] = array_map('intval', explode(',', $request->get('not_tag_ids')));
        }

        return $params;
    }

    /**
     * 获取作者相关参数
     */
    private static function getAuthorParams(Request $request): array
    {
        $params = [];

        if ($request->has('author')) {
            $params['author'] = (int) $request->get('author');
        }
        return $params;
    }

    /**
     * 获取日期相关参数
     *
     * 支持格式：
     * - date: 2024-03-15 (精确日期)
     * - date_from: 2024-03-01 (开始日期)
     * - date_to: 2024-03-31 (结束日期)
     */
    private static function getDateParams(Request $request): array
    {
        $params = [];

        // 精确日期查询
        if ($request->has('date')) {
            $date = $request->get('date');
            if (self::isValidDate($date)) {
                $dateParts = explode('-', $date);
                $params['year'] = (int) $dateParts[0];
                $params['monthnum'] = (int) $dateParts[1];
                $params['day'] = (int) $dateParts[2];
            }
        }

        // 日期范围查询
        if ($request->has('date_from') || $request->has('date_to')) {
            $dateQuery = [];

            if ($request->has('date_from') && self::isValidDate($request->get('date_from'))) {
                $dateQuery['after'] = $request->get('date_from');
            }

            if ($request->has('date_to') && self::isValidDate($request->get('date_to'))) {
                $dateQuery['before'] = $request->get('date_to');
            }

            if (!empty($dateQuery)) {
                $dateQuery['inclusive'] = true;
                $params['date_query'] = [$dateQuery];
            }
        }

        return $params;
    }

    /**
     * 验证日期格式是否为 YYYY-MM-DD
     */
    private static function isValidDate(string $date): bool
    {
        if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
            return false;
        }

        $dateParts = explode('-', $date);
        return checkdate((int) $dateParts[1], (int) $dateParts[2], (int) $dateParts[0]);
    }

    /**
     * 获取搜索相关参数
     */
    private static function getSearchParams(Request $request): array
    {
        $params = [];

        if ($request->has('s')) {
            $params['s'] = $request->get('s');
        }

        return $params;
    }

    /**
     * 获取粘性文章相关参数
     */
    private static function getStickyParams(Request $request): array
    {
        $params = [];

        // 排除粘性文章
        if ($request->has('ignore_sticky_posts')) {
            $params['ignore_sticky_posts'] = (bool) $request->get('ignore_sticky_posts');
        }

        // 只返回粘性文章
        if ($request->get('sticky_only') == '1') {
            $sticky = get_option('sticky_posts');
            if (!empty($sticky)) {
                $params['post__in'] = $sticky;
            }
        }

        return $params;
    }

    /**
     * 验证和清理查询参数
     *
     * @param array $params
     * @return array
     */
    public static function validateAndCleanParams(array $params): array
    {
        // 确保数值类型参数的有效性
        if (isset($params['posts_per_page'])) {
            $params['posts_per_page'] = max(1, min(100, $params['posts_per_page']));
        }

        if (isset($params['paged'])) {
            $params['paged'] = max(1, $params['paged']);
        }

        // 验证排序参数
        $validOrderBy = ['date', 'title', 'menu_order', 'rand', 'ID', 'author', 'name', 'modified', 'comment_count'];
        if (isset($params['orderby']) && !in_array($params['orderby'], $validOrderBy)) {
            $params['orderby'] = 'date';
        }

        $validOrder = ['ASC', 'DESC'];
        if (isset($params['order']) && !in_array($params['order'], $validOrder)) {
            $params['order'] = 'DESC';
        }

        return $params;
    }
}
